package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private MenuService menuService;

    //新增菜单
    @RequestMapping("/add")
    public Result add(@RequestBody Menu menu){
        try {
            menuService.add(menu);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false,"新增菜单失败");
        }
        return  new Result(true,"新增菜单成功");
    }

    //分页查询菜单信息
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = menuService.pageQuery(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        return pageResult;
    }

    //删除菜单
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        return menuService.deleteById(id);
    }

    //编辑菜单
    @RequestMapping("/edit")
    public Result edit(@RequestBody Menu menu) {

        try {
            menuService.edit(menu);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false,"修改菜单失败");
        }
        return new Result(true,"修改菜单成功");
    }

    //通过ID查找菜单
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Menu menu = null;
        try {
            menu = menuService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false,"数据回显失败");
        }
        return new Result(true,"数据回显成功",menu);
    }

    //自关联id初始化
    @RequestMapping("/findAllId")
    public Result findAllId() {
        List<Menu> menuList = null;
        try {
            menuList = menuService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false,"数据回显失败");
        }
        return new Result(true,"数据回显成功",menuList);
    }
}
